<?php
/**
 * 正道项目 - 商品接口类
 * @author   yubo <yubo@ebsig.com>
 * @version 1.0
 */

namespace App\Service\Rpc\Goods;
use DB;
use Carbon\Carbon;
use App\Models\Goods\GoodsImport;  //导入商品表
use GuzzleHttp\Client;
use App\Models\Goods\LogEaiGoods; //商品基础资料表
use App\Models\ConfigureFunction;
use App\Models\Mall\MallMaster;
use App\Models\Goods\GoodsSale;
use App\Models\Wms\WmsGoodsStore;

class KjbGoods
{

    private $http_url = 'http://xxapi.cbtbuy.com:71/';

    public function requestApi($request_url, $api_name, $get_data = [], $post_data = [], $request_way = 'get' )
    {

        //http实例化
        $client = new Client();

        //接口参数
        $data = $this->createSign($post_data);

        /*
         * ==========接口请求==============
         */

        $res = $client->post($request_url ,['form_params'=>[
            'headers' =>[
                'Accept' => 'application/json',
                'Content-Type' => 'multipart/form-data;charset=utf-8'
            ],
            'data' => $data
        ]]);

        $result_array = json_decode($res->getBody(),true);

        $return_data = [];
        if ($result_array['code'] == 0) {
            $return_data['code'] = 200;
            $return_data['data'] = json_decode($this->decrypt($result_array['data']),true);

        } else {
            $return_data['code'] = 400;
        }

        /**
         * =======商品接口日志==========
         */

        $log_interface = new LogEaiGoods();
        $log_interface->uuid = makeUuid();
        $log_interface->timeStamp = Carbon::now();
        $log_interface->creator = 'fuji';
        $log_interface->createTime = Carbon::now();
        $log_interface->bill_no = '';
        $log_interface->product_code = '';
        $log_interface->mallCode = '';
        $log_interface->api_name = $api_name;
        if( !empty($get_data) && !empty($post_data) ){
            $log_interface->request_data = print_r(array_merge($get_data, $post_data), true);
        } else if ( !empty($get_data) ){
            $log_interface->request_data = print_r($get_data, true);
        } else if ( !empty($post_data) ){
            $log_interface->request_data = print_r($post_data, true);
        }
        $log_interface->return_data = print_r($return_data, true);
        $log_interface->return_code = $return_data['code'];
        $log_interface->return_msg  = $result_array['message'];
        $log_interface->exec_time =Carbon::now();
        $log_interface->save();

        /**
         * =======商品接口日志==========
         */

        return $return_data;
    }


    //获取加密签名
    private function createSign($data){

        $cipher = MCRYPT_RIJNDAEL_128;        //加密类型
        $mode = MCRYPT_MODE_ECB;            //加密模式

        $blocksize = mcrypt_get_block_size ( $cipher, $mode );
        $pad = $blocksize - (strlen ( $data ) % $blocksize);
        $str = $data . str_repeat ( chr ( $pad ), $pad );

        $str_encrypt = mcrypt_encrypt($cipher, 'da0205c1e0aa9512', $str, $mode);

        return base64_encode($str_encrypt);

    }

    //解密返回信息
    private function decrypt( $data ){

        $cipher = MCRYPT_RIJNDAEL_128;    //加密类型
        $mode = MCRYPT_MODE_ECB;        //加密模式

        $str = base64_decode($data);

        $str_decrypt = mcrypt_decrypt($cipher, 'da0205c1e0aa9512', $str, $mode);

        $pad = ord($str_decrypt {strlen($str_decrypt) - 1});
        if ($pad > strlen($str_decrypt))
            return false;
        if (strspn($str_decrypt, chr($pad), strlen($str_decrypt) - $pad) != $pad)
            return false;
        $str_decrypt = substr($str_decrypt, 0, - 1 * $pad);

        return $str_decrypt;

    }

    /**
     * 查询线下商品资料
     * @return array
     */
    public function query()
    {
        $page = 1;

        $url = $this->http_url . '/getGoodsList'; //接口地址

        while ($page > 0) {

            $param = [
                'curPage' => $page,
                'pageSize' => 100
            ];

            $goods_data =  $this->requestApi($url,'getGoodsList', [], json_encode($param),'post');
            if( $goods_data['code'] != 200 || empty($goods_data['data']) ){

                die();
            }

            ++$page;

            foreach ($goods_data['data'] as &$goods) {

                $goods_conten = [
                    'mainPostID' => 0,
                    'product_type' => 1,
                    'product_name' => $goods['Name'],
                    'brandID' => 0,
                    'unitID' => 0,
                    'brief' => '',
                    'pc_description' => '',
                    'mobile_description' => '',
                    'bigCategoryID' => 0,
                    'midCategoryID' => 0,
                    'smallCategoryID' => 0,
                    'goods_limit' => 0,
                    'forsale_type' => 0,
                    'supplier_id' => 1,
                    'spec_type' => 0,
                    'WAP' => 1,
                    'PC' => 1,
                    'APP' => 1,
                    'sale' => [
                        0 => [
                            'product_code' => $goods['BarcodeID'],
                            'spec1' => '',
                            'spec2' => '',
                            'sale_price' => '1.00',
                            'market_price' => '1.00',
                            'cost_price' => '0.00',
                            'higher_price' => '',
                            'lower_price' => '0.00',
                            'product_rate' => '',
                            'record_price' => '',
                            'record_code' => '',
                            'customs_product_code' => '',
                            'weight' => 0,
                            'sale_points' => '0',
                            'product_spec' => 1
                        ]
                    ]

                ];

                $product_import = GoodsImport::store( $goods_conten );

                if ($product_import['code'] != 200) {
                    continue;
                }

            }

            /**
             * =======保存数据=========
             */


        }

        return ['code' => 200, 'message' => 'ok'];

    }


    /**
     * 查询线下商品库存
     * @return array
     */
    public function store(){

        $url = $this->http_url . '/getGoodsList'; //接口地址

        //获取库存比率
        $store_ratio = ConfigureFunction::getConfigureField(34, 'store_ratio');
        if (!$store_ratio) {
            $store_ratio = 1;
        }

        //查询门店信息
        $mall = MallMaster::where(['useFlg' => 1]);
        if (!$mall) {
            return ['code' => 100000, 'message' => '门店信息不存在'];
        }

        $page = 1;
        $rp = 100;

        while ($page > 0) {

            $insert_data = [];

            $goodsType = [];

            $goods = GoodsSale::where(['useFlg' => 1, 'forsale' => 1])->offset(($page - 1) * $rp)->limit($rp)->get()->toArray();
            if (!$goods) {
                break;
            }

            if (!isset($goods[$rp - 1])) {
                $page = 0;
            } else {
                $page++;
            }

            $step_code_str = '';
            $customs_code_str = '';
            $product_code_str = '';

            foreach ($goods as $g) {
                if ($g['goodsType'] == 3) {
                    $step_code_str .= $g['product_code'] . ',';
                    $customs_code_str .= $g['customs_product_code'] . ',';
                } else {
                    $product_code_str .= $g['product_code'] . ',';
                }
            }

            if ($product_code_str) {
                $goodsType[] = 0; //普通商品
                $product_code_str = substr($product_code_str,0,-1);
            }

            $step_code_str = '';
            if ($step_code_str) {
                $step_code_str = substr($step_code_str,0,-1);
                $customs_code_str = substr($customs_code_str,0,-1);
                $goodsType[] = 1; //跨境商品
            }

            foreach ($goodsType as $type) {
                foreach ($mall as &$m) {
                    if ($type == 1) {
                        $param = [
                            'barCode' => $step_code_str,
                            'sku' => $customs_code_str,
                            'isCb' => 1
                        ];
                    } else {
                        $param = [
                            'barCode' => $product_code_str,
                            'isCb' => 0
                        ];
                    }
                    $param['shopId'] = $m['mallCode'];

                    $store_data =  $this->requestApi($url,'queryLogistics', [], json_encode($param),'post');
                    if ( $store_data['code'] != 200 || empty($store_data['data']) ) {
                        continue;
                    }


                    //插入库存
                    $insert_wms_sql = 'REPLACE INTO wms_goodsstore (uuid,timeStamp,creator,createTime,mainPostID,storeID,product_code,goodsName,enableSaleAmount,sync_offline_stock,forsale) VALUES ';

                    //插入库存主表
                    $insert_wms_master_sql = 'REPLACE INTO wms_goods_master (uuid,timeStamp,creator,createTime,storeID,mainPostID) VALUES ';

                    $temp_array = array();

                    $fail = 0;

                    foreach($store_data['data'] as $key => $store){


                        $is_store = WmsGoodsStore::where(['storeID' => $m['mallID'], 'product_code' => $store['BarcodeID'], 'sync_offline_stock' => 0])->first();
                        if ($is_store) {
                            continue;
                        }

                        //查询商品
                        $goods_data = GoodsSale::where(['product_code' => $store['BarcodeID']])->get()->toArray();
                        if (!$goods_data) {
                            continue;
                        }

                        $enableSaleAmount = floor($store['Qty'] * $store_ratio);

                        //查询已有订单商品数量
                        $bill_sql = 'SELECT SUM(bg.goods_amount) AS num FROM bill_master bm
                                   INNER JOIN bill_goods bg
                                   ON bm.bill_no = bg.bill_no
                                   WHERE bm.bill_status IN (1, 3) AND bm.mallCode = "'.$mall['mallCode'].'" AND bg.product_code = "'.$store['BarcodeID'].'"';
                        $bill_data = DB::select($bill_sql);
                        if ( $bill_data ) {
                            $enableSaleAmount = $enableSaleAmount - $bill_data[0]['num'];
                        }

                        if ( $enableSaleAmount <= 0 ) {
                            $enableSaleAmount = 0;
                        }

                        $insert_wms_sql .= '("'.makeUuid().'","'.Carbon::now().'","createGoodsStore","'.Carbon::now().'",'.$goods_data[0]['mainPostID'].','.$mall['mallID'].
                            ',"'.$store['BarcodeID'].'","'.$goods_data[0]['goodsName'].'",'.$enableSaleAmount.',1,'.$goods_data[0]['forsale'].'),';

                        if ( !in_array($goods_data[0]['mainPostID'], $temp_array) && ebsig_is_int($goods_data[0]['mainPostID']) ) {
                            $temp_array[] = $goods_data[0]['mainPostID'];

                            $insert_wms_master_sql .= '("'.makeUuid().'","'.Carbon::now().'","createShopGoods","'.Carbon::now().'",'.$mall['mallID'].
                                ','.$goods_data[0]['mainPostID']. '),';
                        }

                        $fail ++;
                    }

                    if ($fail <= 0) {
                        continue;
                    }

                    $insert_data[] = substr($insert_wms_sql,0,-1);
                    $insert_data[] = substr($insert_wms_master_sql,0,-1);

                }

                //分割数组
                $sql_data = array_chunk($insert_data,500);

                try {

                    DB::beginTransaction();

                    if( !empty($sql_data) ){
                        foreach ( $sql_data as $insert_sql ){
                            foreach($insert_sql as $sql){
                                DB::insert($sql);
                            }
                        }
                    }

                    DB::commit();

                } catch (\Exception $e) {
                    DB::rollBack();

                    error_log('跨境宝库存，任务错误信息：'.$e->getMessage());
                    continue;
                }
            }

        }

        return ['code' => 200, 'message' => 'ok'];

    }

    /**
     * 查询线下门店商品价格
     * @return array
     */
    public function price(){

        $url = $this->http_url . '/getGoodsPrice'; //接口地址


        //查询门店信息
        $mall = MallMaster::where(['useFlg' => 1]);
        if (!$mall) {
            return ['code' => 100000, 'message' => '门店信息不存在'];
        }

        $page = 1;
        $rp = 100;

        while ($page > 0) {

            $insert_data = [];

            $goods = GoodsSale::where(['useFlg' => 1, 'forsale' => 1])->offset(($page - 1) * $rp)->limit($rp)->get()->toArray();
            if (!$goods) {
                break;
            }

            if (!isset($goods[$rp - 1])) {
                $page = 0;
            } else {
                $page++;
            }

            $product_code_str = '';
            foreach ($goods as $g) {
                $product_code_str .= $g['product_code'] . ',';
            }

            $product_code_str = substr($product_code_str,0,-1);

            foreach ($mall as &$m) {

                $param = [
                    'barCode' => $product_code_str,
                    'shopId' => $m['mallCode']
                ];

                $price_data =  $this->requestApi($url,'getGoodsPrice', [], json_encode($param),'post');
                if ( $price_data['code'] != 200 || empty($price_data['data']) ) {
                    continue;
                }

                //插入经营策略
                $insert_goods_marketing_sql = 'REPLACE INTO goods_marketing_strategy VALUES ';

                foreach($price_data['data'] as $goods){

                    //查询商品
                    $goods_data = GoodsSale::where(['product_code' => $goods['BarcodeID']])->get()->toArray();
                    if (!$goods_data) {
                        continue;
                    }

                    $salePrice = sprintf("%1.2f", $goods['Price']);
                    $marketPrice = sprintf("%1.2f", $goods['NormalPrice']);

                    $insert_goods_marketing_sql .= '("'.makeUuid().'","'.Carbon::now().'","createPrice","'.Carbon::now().'",'.$goods_data[0]['mainPostID'].
                        ','.$mall['mallID'].','.$goods_data[0]['postID'].',"'.$goods_data[0]['product_code'].'","'.$goods_data[0]['product_spec'].'","'.$goods_data[0]['goodsName'].
                        '","'.$marketPrice.'","'.$salePrice.'",'.$goods_data[0]['salePoints'].'),';

                }

                $insert_data[] = substr($insert_goods_marketing_sql,0,-1);
            }

        }

        //分割数组
        $sql_data = array_chunk($insert_data,500);

        try {

            DB::beginTransaction();

            if( !empty($sql_data) ){
                foreach ( $sql_data as $insert_sql ){
                    foreach($insert_sql as $sql){
                        DB::insert($sql);
                    }
                }
            }

            DB::commit();

        } catch (\Exception $e) {
            DB::rollBack();
            error_log('跨境宝门店价格，任务错误信息：'.$e->getMessage());
        }
    }
}